<script>
// Closures are an extension of the concept of scope. With closures, 
// functions have access to variables that were available in the scope 
// where the function was created.


//Each function executed within the loop will reference
//the last value stored in i (5).
//This won't behave as we want it to - every 100 milliseconds, 5 will alert
for ( var i = 0; i < 5; i++ ) {
	setTimeout(function() { console.log( i ); }, i*100 );
}

//Using a closure to create a new private scope
//fix: “close” the value of i inside createFunction, so it won't change
var createFunction = function( i ) {
	return function() {
		console.log( i );
	};
};
for ( var i = 0; i < 5; i++ ) {
	setTimeout( createFunction( i ), i * 100 );
}




//Using a closure to access inner and outer object instances simultaneously.
var outerObj = {
	myName: "outer",
	outerFunction: function() {
		// Provide a reference to outerObj through innerFunction's closure
		var self = this;
		var innerObj = {
			myName: "inner",
			innerFunction: function() {
				console.log( self.myName, this.myName ); // "outer inner"
			}
		};
		innerObj.innerFunction(); // "outer, inner"
		console.log( this.myName ); // "outer"
	}
};
outerObj.outerFunction();


//Let's manipulate "this" with a basic example.
var user = "johnsmith";
var module = {
	getUser: function() {
		return this.user;
	},
	user: "janedoe"
};
// module.getUser() is called where "module" is "this"
// and "module.user" is returned. 
// janedoe
console.log(module.getUser());

// let's now store a reference in the global version of "this"
// getUser() called, "this" is global, "user" is returned
// johnsmith
var getUser = module.getUser;
console.log(getUser());

// store a ref with "module" bound as "this"
var boundGetUser = getUser.bind( module );
// boundGetUser() called, "module" is "this" again, "module.user" returned.
// janedoe
console.log(boundGetUser());
</script>